import { Injectable, NestMiddleware } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Request, Response, NextFunction } from 'express';
import * as jwt from 'jsonwebtoken';

@Injectable()
export class JwtMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    try {
      // 从请求头获取Authorization
      const authHeader = req.headers.authorization;

      if (authHeader && authHeader.startsWith('Bearer ')) {
        const token = authHeader.substring(7); // 移除 'Bearer ' 前缀

        try {
          // 从环境变量获取JWT密钥
          const jwtSecret = process.env.JWT_SECRET;
          if (!jwtSecret) {
            console.error('❌ JWT中间件 - JWT_SECRET未配置');
            req.user = null;
            return next();
          }

          // 验证JWT token
          const payload = jwt.verify(token, jwtSecret) as any;

          // 将用户信息放入req.user
          req.user = {
            id: payload.sub || payload.id, // 用户ID
            phone: payload.phone,
            email: payload.email,
            nickname: payload.nickname,
            role: payload.role,
            vipExpiredAt: payload.vipExpiredAt
              ? new Date(payload.vipExpiredAt)
              : undefined,
            points: payload.points,
            ...payload, // 包含所有payload信息
          };
        } catch (jwtError) {
          console.log('⚠️  JWT中间件 - Token验证失败:', jwtError.message);
          // Token无效，但不阻止请求继续，只是不设置req.user
          req.user = null;
        }
      } else {
        // 没有Authorization头，设置req.user为null
        req.user = null;
        console.log('ℹ️  JWT中间件 - 无Authorization头');
      }

      next();
    } catch (error) {
      console.error('❌ JWT中间件 - 处理错误:', error.message);
      req.user = null;
      next();
    }
  }
}
